package com.shop.loan.meiqia;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.service.EruptUserDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import xyz.erupt.upms.service.EruptUserService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MeiQiaUtil {

    @Value("${api.service.accessToken}")
    private String accessToken;

    @Value("${api.service.mail}")
    private String mail;

    @Resource
    EruptUserDataService eruptUserDataService;

    @Resource
    EruptUserService eruptUserService;

    public static String url = "https://api.meiqia.com/unified-api/session/v1/sso/login-urls";

    public String loginUrls() {
        if (eruptUserDataService.checkChannelAuth(eruptUserService.getCurrentUid())) {
            //若是渠道 则不允许访问
            return null;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("agent_email", mail);

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Authorization", "Bearer " + accessToken);

        String result = HttpRequest.post(url)
                .addHeaders(headMap)
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("美洽【loginUrls】 参数:{},返回:{}", jsonObject, result);
        JSONObject resultJs = JSON.parseObject(result);
        if (resultJs != null && resultJs.containsKey("url")) {
            return resultJs.getString("url");
        }
        return null;
    }
}
